<!-- 新增黑名单人员 -->
<!-- 职位管理新增组件 -->
<template>
  <a-drawer
    :width="600"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmount-on-close
  >
    <template #title> 新增黑名单人员 </template>
    <div>
      <a-form :model="formData" ref="refForm" :rules="rules" auto-label-width>
        <a-form-item label="类型" field="type" showColon>
          <a-radio-group v-model="formData.type" :disabled="data?.id">
            <a-radio :value="1">内部人员</a-radio>
            <a-radio :value="2">外部人员</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="姓名" field="name" showColon>
          <a-select
            placeholder="请选择"
            v-model="formData.name"
            allow-search
            allow-clear
            @popup-visible-change="showHumanModal"
            :popup-visible="false"
            :disabled="data?.id"
            v-if="formData.type === 1"
          >
            <a-option
              v-for="item in humanList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
          <a-input v-else v-model="formData.name" />
        </a-form-item>
        <a-form-item
          label="工号"
          field="jobNum"
          showColon
          v-show="formData.type === 1"
        >
          <a-input v-model="formData.jobNum" disabled />
        </a-form-item>
        <a-form-item
          label="部门"
          field="departmentId"
          showColon
          v-show="formData.type === 1"
        >
          <a-select
            placeholder="请选择"
            v-model="formData.departmentId"
            disabled
          >
            <a-option
              v-for="item in organizationList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="职位"
          field="positionId"
          showColon
          v-show="formData.type === 1"
        >
          <a-select placeholder="请选择" v-model="formData.positionId" disabled>
            <a-option
              v-for="item in positionList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="手机号码"
          field="mobile"
          showColon
          :disabled="formData.type === 1"
        >
          <a-input v-model="formData.mobile" />
        </a-form-item>
        <a-form-item label="证件类型" field="idType" showColon>
          <a-select
            placeholder="请选择"
            v-model="formData.idType"
            :disabled="formData.type === 1"
          >
            <a-option
              v-for="item in ID_TYPE"
              :key="item"
              :value="item"
              :label="item"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="证件号码" field="idNum" showColon>
          <a-input v-model="formData.idNum" :disabled="formData.type === 1" />
        </a-form-item>
        <a-form-item label="添加原因" field="reason" showColon>
          <a-textarea
            v-model="formData.reason"
            allow-clear
            :max-length="300"
            :auto-size="{
              minRows: 3
            }"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
  <HumanRosterModal
    v-model:visible="humanModalVisible"
    @humanRosterEmit="humanRosterEmit"
    typeName="7"
  />
</template>

<script lang="ts" setup>
import { dataTreeFilter } from '@/utils/utils';
import {
  getPositionFlatList,
  getFlatDept,
  getAllHumanRoster,
  getHumanDetail
} from '@/utils/common';
import { validateRules } from '@/utils/common';
import { GetBlacklist } from '@/apis/management/human/humanChange/blacklist';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import { ID_TYPE } from '@/utils/constants';
import { getControlValue } from '@/utils/control';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data: any; // 传进来的数据
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'blacklistAddEmit']);

// 职位名称查重
const validateName = async (val: any, cb: any, type: number) => {
  try {
    // if (!val) return;
    // let data = {
    //   name: val,
    //   id: formData.value.organizationId
    // };
    // const res = await validateRules(CheckPositionList, data);
    // if (res.code) {
    //   cb(`${res.msg}`);
    // } else return;
  } catch (error: unknown) {
    console.log(error);
  }
};

let refForm = ref(); // 储存表单的ref
const rules = {
  type: [
    {
      required: true,
      message: '请选择'
    }
  ],
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  mobile: [
    {
      required: true,
      message: '请输入'
    },
    {
      match: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      message: '请输入正确的手机号'
    }
  ],
  idNum: [
    {
      match:
        /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
      message: '请输入正确的证件号码'
    }
  ]
};

let formData = ref({
  type: 1, //1 内部员工 2 外部员工
  name: '', // 姓名
  jobNum: '', // 工号
  departmentId: undefined, // 部门id
  positionId: undefined, // 职位id
  mobile: undefined, // 手机号码
  idType: undefined, // 证件类型
  idNum: undefined, // 证件号码
  reason: '' // 添加原因
});

const initData = cloneDeep(formData.value); // 储存初始数据
watch(
  () => props.visible,
  (newVal: boolean) => {
    if (newVal) {
      if (props.data?.id) {
        formData.value = cloneDeep(props.data);
        //
      } else {
        formData.value = cloneDeep(initData);
      }
      getData();
    }
  }
);

let organizationList = ref<any>([]); // 储存部门数据
let positionList = ref(); // 储存职位列表数据
let humanList = ref(); // 储存人员列表
let humanModalVisible = ref(false); // 判断是否显示人员弹框
let blacklistList = ref([]);
const getData = async () => {
  try {
    const [
      // 获取所有组织
      organizationListRes,
      // 获取职位列表
      positionListRes,
      // 获取人员
      humanListRes,
      // 获取所有黑名单人员
      blacklistListRes
    ] = await Promise.all([
      // GetOrganizationList({}),
      getFlatDept(),
      getPositionFlatList(),
      getAllHumanRoster(),
      GetBlacklist({
        pageNumber: 0,
        pageSize: -1
      })
    ]);
    organizationList.value = organizationListRes; // 启用状态下的组织才能被选择
    positionList.value = positionListRes;
    humanList.value = humanListRes;
    blacklistList.value = blacklistListRes.content;
  } catch (error) {
    console.log(error);
  }
};

// 显示人员弹框
const showHumanModal = () => {
  humanModalVisible.value = true;
};

const humanRosterEmit = (record: any) => {
  // 判断选择的人员和现有的黑名单人员是否重复
  const ind = blacklistList.value.findIndex(
    (item: any) => item.createBy === record.id
  );
  if (ind !== -1) {
    Message.error('该人员已在黑名单中,请重新选择!');
    return;
  }
  getHumanInfo(record.id);
};

const getHumanInfo = async (id: number) => {
  try {
    let tempReason = '';
    tempReason = formData.value.reason;
    const res = await getHumanDetail(id);
    res.createBy = res.id;
    delete res.id;
    res.ctlValue.forEach((item: any) => {
      delete item.id;
      delete item.ownerId;
    });
    formData.value = res;
    formData.value.reason = tempReason;
    formData.value.type = 1;
    formData.value.idType =
      getControlValue(
        res?.useTemplate?.collectionModel,
        'C6413B1A7762943709D65A4DF52CD09FD'
      ) || '';
    formData.value.idNum =
      getControlValue(
        res?.useTemplate?.collectionModel,
        'C36FFB1152EBD42B7AD4EF65A6C334A6D'
      ) || '';
  } catch (error) {
    console.log(error);
  }
};

// 保存
const handleOk = async () => {
  if (await refForm.value.validate()) {
    emit('update:visible', true);
    return;
  }
  emit('blacklistAddEmit', formData.value);
  formData.value = cloneDeep(initData);
  emit('update:visible', false);
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
  formData.value = cloneDeep(initData);
};
</script>

<style scoped lang="less"></style>
